package org.opensuse.bs.ui.actions;

import java.io.File;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.resources.WorkspaceJob;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IViewActionDelegate;
import org.eclipse.ui.IViewPart;
import org.opensuse.bs.ui.BSUIPlugin;
import org.opensuse.bs.ui.OSC;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class AddAction implements IViewActionDelegate {
	
	private class NewProjectDialog extends Dialog {
		private Text projectName;
		private Text title;
		private Text des;
		private Combo baseProject;
		
		protected NewProjectDialog(Shell parentShell) {
			super(parentShell);
		}
		
		protected Control createDialogArea(Composite parent) {
			Composite client = new Composite(parent, SWT.NONE);
			GridLayout layout = new GridLayout();
			client.setLayout(layout);
			layout.numColumns = 2;
			
			Label label4 = new Label(client, SWT.NONE);
			label4.setText("Base Project");
			baseProject = new Combo(client, SWT.BORDER|SWT.SIMPLE);
			//get involved project
			String[] result = BSUIPlugin.getDefault().getInvolvedProject();
			for(String one : result) {
				baseProject.add(one);
			}				
			GridData gd = new GridData();
			baseProject.setLayoutData(gd);
			gd.grabExcessHorizontalSpace = true;
			gd.horizontalAlignment = SWT.FILL;
			
			Label label1 = new Label(client, SWT.NONE);
			label1.setText("Sub Project: ");
			projectName = new Text(client, SWT.BORDER);
			gd = new GridData();
			projectName.setLayoutData(gd);
			gd.grabExcessHorizontalSpace = true;
			gd.horizontalAlignment = SWT.FILL;
			projectName.setToolTipText(
					"If you're just a simple user of build service,\n" +
					"you should first create a home project named\n" +
					"home:<login name>.");
			
			Label label2 = new Label(client, SWT.NONE);
			label2.setText("Title: ");
			title = new Text(client, SWT.BORDER);
			gd = new GridData();
			title.setLayoutData(gd);
			gd.grabExcessHorizontalSpace = true;
			gd.horizontalAlignment = SWT.FILL;
			
			Label label3 = new Label(client, SWT.NONE);
			label3.setText("Description: ");
			des = new Text(client, SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL);
			gd = new GridData();
			des.setLayoutData(gd);
			gd.grabExcessHorizontalSpace = true;
			gd.horizontalAlignment = SWT.FILL;
			gd.heightHint = 100;
			
			return client;
		}
		
		protected  void 	okPressed() {
			final IWorkspace workspace = ResourcesPlugin.getWorkspace();
			final IWorkspaceRoot workspaceRoot = workspace.getRoot();
			String name = "";
			int selected = baseProject.getSelectionIndex();
			if(selected != -1)
				name = baseProject.getItem(selected)+":";
			name += projectName.getText().trim();
			String titlen = title.getText().trim();
			String desn = des.getText().trim();
			
			final IProject project = workspaceRoot.getProject(name);
			if(!project.exists()) {
				try {
					DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
					DocumentBuilder builder = factory.newDocumentBuilder();
					Document doc = builder.newDocument();
					
					Element prj = doc.createElement("project");
					prj.setAttribute("name", name);
					doc.appendChild(prj);
					Element title = doc.createElement("title");
					title.setTextContent(titlen);
					prj.appendChild(title);
					Element des = doc.createElement("description");
					des.setTextContent(desn);
					prj.appendChild(des);
					String user = BSUIPlugin.getDefault().getUser();
					Element person = doc.createElement("person");
					person.setAttribute("role", "maintainer");
					person.setAttribute("userid", user);
					prj.appendChild(person);
					person = doc.createElement("person");
					person.setAttribute("role", "bugowner");
					person.setAttribute("userid", user);
					prj.appendChild(person);
					
					File file = OSC.toFile(doc, "AddNewProject");
					Vector<String> result = OSC.run("meta prj "+name+" -F " +file.getAbsolutePath());
					file.delete();
					if(result.isEmpty())return;
					final String pn = name;
					WorkspaceJob job = new WorkspaceJob("Creating Project "+pn) {
						public IStatus runInWorkspace(IProgressMonitor monitor)
								throws CoreException {
							String root = workspaceRoot.getLocation().toOSString();
							File rootPath = new File(root);
							Vector<String>result = OSC.run("co "+pn, null, rootPath);
							if(result.isEmpty())return Status.CANCEL_STATUS;
							IProjectDescription pd = workspace.newProjectDescription(pn);
							pd.setComment("Build Service");
							pd.setNatureIds(new String[]{"org.opensuse.bs.ui.bsprojectnature"});
							project.create(pd, monitor);
							if(!project.isOpen())
								project.open(monitor);
							return Status.OK_STATUS;
						}
					};
					job.schedule();
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
			close();
		}
	}
	
	public void init(IViewPart view) {
	}
	
	public void run(IAction action) {
		Dialog dialog = new NewProjectDialog(null);
		dialog.open();
	}
	
	public void selectionChanged(IAction action, ISelection selection) {
	}

}
